require.config({
    paths: {
        'editable': '../libs/bootstrap-table/dist/extensions/editable/bootstrap-table-editable.min',
        'x-editable': '../addons/workteam/js/bootstrap-editable.min',
    },
    shim: {
        'editable': {
            deps: ['x-editable', 'bootstrap-table']
        },
        "x-editable": {
            deps: ["css!../addons/workteam/css/bootstrap-editable.css"],
        }
    }
});

var calendar = null;

define(['jquery', 'bootstrap', 'backend', 'addtabs', 'table', 'echarts', 'echarts-theme', 'template', 'form', 'editable'], function ($, undefined, Backend, Datatable, Table, Echarts, undefined, Template, Form,Editable) {
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'workteam/dashboard/mytask' + location.search,
                    add_url: 'workteam/task/add',
                    edit_url: '',
                    del_url: '',
                    multi_url: '',
                    start_url: 'workteam/task/start',//开始任务和修改进度都是这里
                    table: 'workteam_task',
                }
            });

            var table = $("#table");
            //tab-my-task
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                //禁用默认搜索
                search: false,
                //启用普通表单搜索
                commonSearch: false,
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: false,
                //分页大小
                pageSize: 10,
                showColumns: false,
                showToggle: false,
                showExport: false,
                showSearch: false,
                pagination: true,
                queryParams: function (params) { // 请求服务器数据时发送的参数，可以在这里添加额外的查询参数，返回false则终止请求
                    var activeobj= $('#tab-my-task .active a[data-toggle="tab"]');
                    params.filter= JSON.stringify($(activeobj).data('filter'));
                    params.op= JSON.stringify(activeobj.data('op'));
                    return params
                },
                columns: [
                    [
                        {field: 'project.name', title: __('项目'),operate:false},

                        {field: 'name', title: __('任务')
                            ,customField: 'level'
                            ,formatter: function (value, row, index) {
                                //判断是否逾期
                                var newtime = Math.round(new Date().getTime()/1000).toString();
                                if (newtime>row.end_time&&row.status!=2)
                                    value='<span class="label label-danger">逾</span>'+value;
                                return value +
                                    Controller.api.level(row['level'], row, index,this);
                            }},

                        {field: 'plan_hours', title: __('计划'), operate: 'BETWEEN', sortable: true},
                        {field: 'get_hours', title: __('可得'), operate: 'BETWEEN', sortable: true},
                        {
                            field: 'progress',
                            title: __('进度'),
                            editable: true,
                            operate: false,
                            formatter: function (value, row, index) {
                                var str =value+'%';
                                return str;
                            }
                        },
                        {field: 'status', title: __('状态'), searchList: Config.statusList, formatter: Table.api.formatter.status},
                        {field: 'start_time', title: __('开始'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime,sortable: true},
                        {field: 'end_time', title: __('截止'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime,sortable: true},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'start',
                                    text: '',
                                    title: __('开始任务'),
                                    icon: 'fa fa-play-circle-o',
                                    confirm: __("确认开始任务"),
                                    classname: 'btn btn-xs btn-info btn-ajax',
                                    url: 'workteam/task/start',
                                    hidden:function (row) {
                                        if (row.status!=0) return true;
                                    },
                                    success:function () {
                                        table.bootstrapTable('refresh');
                                    }
                                },
                                {
                                    name: 'complete',
                                    text: '',
                                    title: __('完成任务'),
                                    icon: 'fa fa-check-circle',
                                    // classname: 'btn btn-xs btn-info btn-ajax',
                                    // confirm: __("确认完成任务？完成之后不能再操作"),
	                                classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'workteam/task/complete',
                                    hidden:function (row) {
                                        if (row.status!=1) return true;
                                    },
                                    success:function () {
                                        table.bootstrapTable('refresh');
                                    }
                                },
                                {
                                    name: 'addchild',
                                    text: '',
                                    title: __('添加子任务'),
                                    icon: 'fa fa-plus',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: 'workteam/task/addchild',
                                    hidden:function (row) {
                                        if (row.status==2) return true;
                                    },
                                },
                                {
                                    name: 'detail',
                                    text: '',
                                    title: __('任务详情'),
                                    icon: 'fa fa-info-circle',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    url: 'workteam/task/detail',
                                },
                            ]}
                    ]
                ],
                onEditableSave:function (field, row, oldValue, $el) {

                    var data = {};
                    data[field] = row[field];
                    Fast.api.ajax({
                        url: $.fn.bootstrapTable.defaults.extend.start_url + "/ids/" + row[this.pk],
                        data: data
                    },function () {
                        $(".btn-refresh").trigger("click");
                    });
                },
                //启用固定列
                fixedColumns: true,
                //固定右侧列数
                fixedRightNumber: 1,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            // 绑定TAB事件
            $('#tab-my-task a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

                table.bootstrapTable('refresh', {pageNumber: 1});
                return false;
            });



            var table1 = $("#table1");

            // 初始化表格
            table1.bootstrapTable({
                url: 'workteam/dashboard/myproject' ,
                pk: 'id',
                sortName: 'id',
                //禁用默认搜索
                search: false,
                //启用普通表单搜索
                commonSearch: false,
                //可以控制是否默认显示搜索单表,false则隐藏,默认为false
                searchFormVisible: false,
                //分页大小
                pageSize: 10,
                showColumns: false,
                showToggle: false,
                showExport: false,
                showSearch: false,
                pagination: true,
                queryParams: function (params) { // 请求服务器数据时发送的参数，可以在这里添加额外的查询参数，返回false则终止请求
                    var activeobj= $('#tab-my-project .active a[data-toggle="tab"]');
                    params.filter= JSON.stringify($(activeobj).data('filter'));
                    params.op= JSON.stringify(activeobj.data('op'));
                    return params
                },
                columns: [
                    [
                        {field: 'name', title: __('名称')
                            ,customField: 'level'
                            ,formatter: function (value, row, index) {
                                //判断是否逾期
                                var newtime = Math.round(new Date().getTime()/1000).toString();
                                if (newtime>row.end_time&&row.status!=2)
                                    value='<span class="label label-danger">逾</span>'+value;
                                return value +
                                    Controller.api.level(row['level'], row, index,this);
                            }},
                        {field: 'customer_name', title: __('客户名称')},
                        {field: 'remark', title: __('备注')},
                        {
                            field: 'progress',
                            title: __('进度'),
                            operate: false,
                            formatter: function (value, row, index) {
                                var plan_hours_p='0%';
                                if (row.plan_hours<row.task_hours){
                                    row.plan_hours=row.task_hours;
                                }
                                plan_hours_p=(row.actual_hours/row.plan_hours)*100;
                                plan_hours_p=plan_hours_p.toFixed(2)
                                var str ='<div class="progress" ><div class="progress-bar" style="width:'+plan_hours_p+'%;">'+plan_hours_p+'%</div></div>';
                                return str;
                            }
                        },

                        {field: 'plan_hours', title: __('计划工时'), operate: 'BETWEEN', sortable: true},
                        {field: 'plan_hours', title: __('实际工时'), operate: 'BETWEEN', sortable: true},
                        {field: 'task_count', title: __('任务总量'), operate: 'BETWEEN', sortable: true},
                        {field: 'task_complate', title: __('完成数量'), operate: 'BETWEEN', sortable: true},

                        {field: 'status', title: __('Status'), searchList: Config.statusList, formatter: Table.api.formatter.status},
                        {field: 'start_time', title: __('开始日期'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime,sortable: true},
                        {field: 'end_time', title: __('截止日期'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime,sortable: true},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    text: '详情',
                                    title:function (row) {
                                        return __('项目:')+row.name;
                                    },
                                    icon: '',
                                    classname: 'btn btn-xs btn-primary btn-addtabs',
                                    url: 'workteam/project/detail',

                                },
                                {
                                    name: 'task',
                                    text: '',
                                    title: __('添加任务'),
                                    icon: 'fa fa-plus',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: 'workteam/task/add',
                                },
                            ]}
                    ]
                ],
                //启用固定列
                fixedColumns: true,
                //固定右侧列数
                fixedRightNumber: 1,
            });

            // 为表格绑定事件
            Table.api.bindevent(table1);

            // 绑定TAB事件
            $('#tab-my-project a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                table1.bootstrapTable('refresh', {pageNumber: 1});
                return false;
            });


            require.config({
                    paths: {
                        'Gzyechart': '../addons/workteam/js/gzyechart',
                    }
                }
            );
            require(['Gzyechart'], function () {
                Form.api.bindevent($("form[role=form]"));
                // 基于准备好的dom，初始化健康表格数据
                Gzyechart.echart.loadEchart("hours", Echartdata.hours.date, Echartdata.hours.data);
                Gzyechart.echart.initButton();
                $(document).on("change", "#c-owner_user_id", function () {
                    var owner_user_id = $(this).val();
                    var datetimerange = $(this).parent().parent().find(".datetimerange");
                    var url = datetimerange.data('url');
                    if (url.indexOf("owner_user_id") != -1) {
                        url = Controller.api.replaceParamVal(url, "owner_user_id", owner_user_id);
                    } else {
                        url = url + "&owner_user_id=" + owner_user_id;
                    }
                    datetimerange.data('url', url);
                });
            });

        },
        api: {
            level: function (value, row, index,obj) {
                if (value==1) return '';
                var colorArr = ["primary", "success", "default", "info", "warning", "danger", "red", "yellow", "aqua", "blue", "navy", "teal", "olive", "lime", "fuchsia", "purple", "maroon"];

                var field = obj.field;
                if (typeof obj.customField !== 'undefined' && typeof row[obj.customField] !== 'undefined') {
                    field = obj.customField;
                }
                var color = index > -1 && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
                var icon='',display=Config.levelList[value];
                var html = '<span class="label label-' + color + '">' + display + '</span>';
                if (obj.operate != false) {
                    html = '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', display) + '" data-field="' + field + '" data-value="' + value + '">' + html + '</a>';
                }
                return html;
            },
        }
    };

    return Controller;
});
